package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type User struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	Age    int    `json:"age"`
	Social Social `json:"social"`
}

type Social struct {
	Facebook string `json:"facebook"`
	Twitter  string `json:"twitter"`
}

type UserList struct {
	Users []User `json:"users"`
}

func (ul *UserList) FormatPrint() {
	for _, u := range ul.Users {
		fmt.Println("User Type:", u.Type)
		fmt.Println("User Age:", u.Age)
		fmt.Println("User Name:", u.Name)
		fmt.Println("Facebook Url:", u.Social.Facebook)
	}
}

func main() {
	filename := "/Users/sundebiao/gocode/src/go_actual_battalion/json2struct/users.json"

	//jsonStr, err := ioutil.ReadFile(filename)
	//if err != nil {
	//	panic(fmt.Sprintf("users.json error: %s", err))
	//}

	//f, err := os.Open(filename)
	f, err := os.OpenFile(filename, os.O_RDONLY, 0755)
	defer f.Close()
	if err != nil {
		panic(fmt.Sprintf("users.json error: %s", err))
	}
	//读取的json数据会有空字节，需要使用切片去掉，才能正常解析，不然会报错
	//json unmarshal error: invalid character '\x00' after top-level value
	jsonByte := make([]byte, 512)
	n, err := f.Read(jsonByte)
	if err != nil {
		panic(fmt.Sprintf("json read error: %s", err))
	}
	jsonStr := jsonByte[:n]

	fmt.Println("Successfully opened users.json")

	var userList UserList
	if err = json.Unmarshal(jsonStr, &userList); err != nil {
		panic(fmt.Sprintf("json unmarshal error: %s", err))
	}

	userList.FormatPrint()
	fmt.Printf("%v\n", userList)
}
